import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Search } from "react-vant";
import style from "./index.module.scss";
import axios from "../../../http/axios";
import { Button, Space } from "antd-mobile";
// 导入节流防抖函数
import { throttle, debounce } from "lodash";

const Index: React.FC = () => {
  const navigate = useNavigate();
  const [wd, setWd] = useState("");
  const [List, setList] = useState([]);
  const [hisdatalist, setHisdatalist] = useState<string[]>(
    JSON.parse(localStorage.getItem("kphhistory") || "[]")
  );

  const search = async (value: string) => {
    setWd(value);
    // 历史搜索记录
    const index = hisdatalist.lastIndexOf(value);
    if (index > -1) {
      hisdatalist.splice(index, 1);
    }
    hisdatalist.unshift(value);
    localStorage.setItem("kphhistory", JSON.stringify(hisdatalist));
    if (value !== "") {
      const res = await axios.get("/api/date", { params: { wd: value } });
      console.log(res);
      const { data } = res.data;
      setList(data);
    }
  };

  // 使用防抖包装搜索函数
  const debouncedSearch = debounce(search, 1000);

  const tz = () => {
    navigate("/kepuhaodating");
  };

  return (
    <div>
      <div className={style.top}>
        <div>
          <Search
            shape="round"
            background="#fff"
            value={wd}
            onChange={(value: any) => debouncedSearch(value)} // 修改为onInput
            placeholder="可输入科普号名字查找"
          />
        </div>
        <div className={style.btbt}>
          <Button
            size="mini"
            color="primary"
            className={style.btn}
            onClick={() => tz()}
          >
            取消
          </Button>
        </div>
      </div>

      {/* 历史搜索记录 */}
      <div>
        {wd ? (
          ""
        ) : (
          <div>
            <h5>历史搜索</h5>
            <div className={style.Searchlist}>
              <ul>
                {hisdatalist.map((item, ind) => {
                  return <li key={ind}>{item}</li>;
                })}
              </ul>
            </div>
          </div>
        )}
      </div>

      {/* 搜索结果 */}
      <div>
        {List.length > 0 &&
          List.map((item: any, ind) => {
            return (
              <div className={style.list} key={ind}>
                <div className={style.listitem}>
                  <div>
                    <img src={item.image} alt="" />
                  </div>
                  <div>
                    <div className={style.name1}>{item.name}医生的科普号</div>
                    <span>
                      {item.name} {item.type} {item.keshi} {item.hospital}
                    </span>
                  </div>
                </div>
              </div>
            );
          })}
      </div>
    </div>
  );
};

export default Index;
